package com.sdkj.controller;

import com.sdkj.mapper.OrdersettingMapper;
import com.sdkj.pojo.Ordersetting;
import com.sdkj.service.OrdersettingService;
import com.sdkj.util.MessageConstant;
import com.sdkj.util.POIUtils;
import com.sdkj.util.Result;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/ordersetting")
public class OrdersettingController {
    @Resource
    private OrdersettingService ordersettingService;
    @Resource
    private OrdersettingMapper ordersettingMapper;

    @RequestMapping("/uploadTempleate")
    public Result uploadTempleate(@RequestParam("excelFile") MultipartFile excelFile){
        try{
            List<String[]> dataInfo = POIUtils.readExcel(excelFile);
            // [[“2024/10/22”,"300"],[“2024/10/23”,"300"],[“2024/10/24”,"300"]..]
            boolean flag = ordersettingService.saveOrdersettingInfo(dataInfo);
            if (flag){
                return  new Result(true, MessageConstant.UPLOAD_SUCCESS);
            }else{
                return  new Result(false,"上传数据失败");
            }
        }catch (Exception ex){
            ex.printStackTrace();
            return  new Result(false,"上传数据失败");
        }
    }
    //回显预约信息
    @RequestMapping("/getOrdersettingInfo")
    public Result getOrdersettingInfo(String date) {
        // "2024-10"
        List<Map<String, Object>> list = ordersettingService.getOrdersettingInfo(date);
        return new Result(true, "", list);
    }
    //单独修改某一天的预约人数
    @RequestMapping("/updateOrdersettingInfo")
    public Result updateOrdersettingInfo(String date ,Integer number){
        boolean flag = ordersettingService.updateOrdersettingInfo(date,number);
        if (flag){
            return  new Result(flag,"更新数据成功");
        }else{
            return  new Result(flag,"更新数据失败");
        }
    }
    @GetMapping("/download")
    public void downloadOrdersetting(HttpServletResponse response) {
        try {
            // 设置响应头，告知浏览器返回的是一个 Excel 文件
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            String fileName = "OrderSettings.xlsx"; // 文件名
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

            // 加载模板文件
            InputStream templateStream = getClass().getResourceAsStream("/resources/template/ordersetting_template.xlsx");
            try (XSSFWorkbook workbook = new XSSFWorkbook(templateStream);
                 OutputStream out = response.getOutputStream()) {

                XSSFSheet sheet = workbook.getSheetAt(0); // 获取第一个表单

                // 清空原有数据（如果需要）
                int lastRowNum = sheet.getLastRowNum();
                for (int i = 1; i <= lastRowNum; i++) { // 从第1行开始，假设第0行是表头
                    XSSFRow row = sheet.getRow(i);
                    if (row != null) {
                        sheet.removeRow(row);
                    }
                }

                // 获取所有预约信息
                List<Ordersetting> ordersettings = ordersettingMapper.selectList(null); // 获取所有数据

                // 填充数据
                int rowNum = 1; // 从第1行开始填充数据（假设第0行为表头）
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); // 日期格式化
                for (Ordersetting ordersetting : ordersettings) {
                    XSSFRow row = sheet.createRow(rowNum++);
                    row.createCell(0).setCellValue(dateFormat.format(ordersetting.getOrderdate())); // 格式化日期
                    row.createCell(1).setCellValue(ordersetting.getNumber());
                    row.createCell(2).setCellValue(ordersetting.getReservations());
                }

                // 写入输出流
                workbook.write(out);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }



}
